<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: LoanResultController.php
// +----------------------------------------------------------------------
// | Author: liuju
// +----------------------------------------------------------------------
// | Description:  获取用户放款结果
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2019-01-08 Author: liuju Modification: 创建
// +----------------------------------------------------------------------

namespace App\Http\Controllers\Backend\Financial;


use App\Events\UserLoanApplyEvent;
use App\Exceptions\GeneralException;
use App\Facades\CommonPlatformRequestFacade;
use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\Loan\ActionLoanException;
use App\Http\Requests\Backend\Loan\LoanResultListRequest;
use App\Library\Tools\ExcelExport;
use App\Models\HandleLoanException;
use App\Models\LoanApply;
use App\Models\UserBankCard;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;

class LoanResultController extends Controller
{


    public function __construct()
    {
//        $this->middleware('auth:backend');
        $this->user = auth('backend')->user();
    }


    /**
     * Description: 获取放款结果
     * Author: liuju
     * DateTime: 2019-01-09 17:25
     * @param LoanResultListRequest $request
     * @return array
     */
    public function getResultList(LoanResultListRequest $request)
    {
        $pageSize = $request->get('page_size', 25);
        $pageNum = $request->get('page', 1);

        $timeStart = $request->get('time_start', '');
        $timeEnd = $request->get('time_end', '');
        $loanApplyModel = new LoanApply();
        $data = $loanApplyModel->getList($timeStart, $timeEnd, $pageNum, $pageSize);
        return respond($data);
    }


    /**
     * Description: 通过一个日期获取成功的放款结果
     * Author: liuju
     * DateTime: 2019-01-09 20:13
     * @param LoanResultListRequest $request
     * @param $date
     * @return array
     */
    public function getRecordByDate(LoanResultListRequest $request)
    {
        $date = $request->query('date');
        if (empty($date)) {
            return failed('请求失败，缺少具体日期');
        }
        $pageSize = $request->get('page_size', 25);
        $pageNum = $request->get('page', 1);
        $loanApplyModel = new LoanApply();
        $loanApplyModel->setConnection('backend');
        $data =  $loanApplyModel->getLoanSuccessRecodeByDay($date, $pageNum, $pageSize);
        return respond($data);
    }


    /**
     * Description: 获取放款异常记录
     * Author: liuju
     * DateTime: 2019-01-12 11:59
     * @param LoanResultListRequest $request
     * @return mixed
     */
    public function loanChangeCardList(LoanResultListRequest $request)
    {
        $pageSize = $request->get('page_size', 25);
        $pageNum = $request->get('page', 1);

        $timeStart = $request->get('time_start', '');
        $timeEnd = $request->get('time_end', '');

        $data = LoanApply::getChangeCardList($timeStart, $timeEnd, $pageNum, $pageSize);
        return respond($data);
    }


    public function  export(LoanResultListRequest $request)
    {
        $timeStart = $request->get('time_start', '');
        $timeEnd = $request->get('time_end', '');
        $data = LoanApply::getChangeCardList($timeStart,$timeEnd,0,'');
        if(!$data['list']){
            return failed('暂无需要导出的数据');
        }
        $header = ['数据日期','时间','tradeId','loanId','资金方','借款金额','期数','用户','电话','失败卡号','失败原因','新卡号','当前状态'];
        $fields = ['created_date','created_time','trade_id','loan_id','channel_name','amount','period','card_username','phone_num','fail_card_num','message','new_card_num','status_text'];

        $excel = new  ExcelExport($data['list'],$header,$fields);
        $excel->export();
    }


    /**
     * Description:处理用户放款异常
     * Author: liuju
     * DateTime: 2019-01-12 15:06
     * @param ActionLoanException $request
     * @return mixed
     * @throws GeneralException
     * @throws \Throwable
     */
    public function handleLoan(ActionLoanException $request,$loanId)
    {
        $loanApplyModel = new LoanApply();
        $loanApplyModel->setConnection('backend');
        $loanApply = $loanApplyModel->where('id', $loanId)
            ->where('loan_status', LoanApply::LOAN_CHANGE_CARD)
            ->first();
        if (empty($loanApply)) {
            return failed('请求有误，该放款异常数据不存在或状态已变更');
        }

        $loanStatus = $request->get('loan_status');
        //记录处理结果表
        $params = [
            'loan_apply_id' => $loanApply->id,
            'loan_status_before' => $loanApply->loan_status,
            'loan_apply_bank_card_id' => $loanApply->bank_card_id,
            'handle_user_id' => $this->user->id,
            'ip' => $request->getClientIp(),
        ];

        switch ($loanStatus) {
            //修改放款状态为成功
            case  LoanApply::LOAN_HANDLE_CHANGE_CARD_SUCCESS:
                $loanApply->loan_status = $params['loan_status_after'] = LoanApply::LOAN_HANDLE_CHANGE_CARD_SUCCESS;
                $loanMoney = $request->get('loan_money');
                if (!$loanMoney) {
                    return failed('缺少放款成功具体金额');
                }
                if($loanMoney >= $loanApply->amount){
                    return failed('到款金额需要小于放款金额');
                }
                $loanApply->arrival_account = $params['loan_money'] = $loanMoney;
                //如果没有前置险，默认为总金额减去到账金额
                if(!intval($loanApply->pre_insurance_amt)){
                    $loanApply->pre_insurance_amt = floatval($loanApply->amount - $loanApply->arrival_account);
                }
                $loanTime = $request->get('loan_time');
                if (!$loanTime) {
                    return failed('缺少放款成功具体时间');
                }
                $params['handle_loan_time'] = $loanTime;
                $bankCardNum = $request->get('bank_card_num');
                if (!$bankCardNum) {
                    return failed('缺少具体放款银行卡号');
                }
                $getCard = UserBankCard::where('card_num', $bankCardNum)->where('uid', $loanApply->user_id)->where('is_credit', UserBankCard::CREDIT_NO)->first(['id', 'card_num', 'hold_agreement_num']);
                if (!$getCard) {
                    return failed('该银行卡未在用户绑定的储蓄银行卡列表内,请确认银行卡号');
                }
                //验证银行卡协议号是否还有效
                $checkHoldAgreementNum = CommonPlatformRequestFacade::checkHoldAgreement($getCard->hold_agreement_num);
                if ($checkHoldAgreementNum['code'] !== '01') {
                    return failed($checkHoldAgreementNum['message']);
                }
                $params['handle_bank_card_id'] = $getCard->id;
                break;
            //修改放款状态为处理中
            case  LoanApply::LOAN_CHANGE_CARD_HANDLING:
                $loanApply->loan_status = $params['loan_status_after'] = LoanApply::LOAN_CHANGE_CARD_HANDLING;
                break;
            //修改放款状态为失败
            case LoanApply::LOAN_HANDLE_CHANGE_CARD_FAIL:
                $loanApply->loan_status = $params['loan_status_after'] = LoanApply::LOAN_HANDLE_CHANGE_CARD_FAIL;
                break;
            default:
                break;
        }

        try {
            $loanApply->saveOrFail();
            event(new UserLoanApplyEvent($loanApply));
            HandleLoanException::create($params);
            return success([], [], '操作成功');
        } catch (\Exception $e) {
            throw  new GeneralException($e->getMessage());
        }
    }


    /**
     * Description: 获取处理状态映射列表
     * Author: liuju
     * DateTime: 2019-01-12 16:30
     * @return mixed
     */
    public function getLoanStatusList()
    {
        return respond([
            LoanApply::LOAN_CHANGE_CARD => '处理',
            LoanApply::LOAN_CHANGE_CARD_HANDLING => '处理中',
            LoanApply::LOAN_HANDLE_CHANGE_CARD_SUCCESS => '处理成功',
            LoanApply::LOAN_HANDLE_CHANGE_CARD_FAIL => '处理失败',
        ]);
    }

}